package control

import (
	"bms/model"
	"bms/service"
	"html/template"
	"log"
	"net/http"
	"strconv"
	"time"
)

func BorrowBook(w http.ResponseWriter, r *http.Request) {
	flag, session := IsLogin(r)
	if flag {
		bookId, _ := strconv.Atoi(r.FormValue("bookId"))
		//根据bookId查找图书,然后添加到我的借阅列表里
		book, err := service.BorrowBook(int64(bookId))
		if err != nil {
			book = &model.Book{}
		}
		//判断该用户是否已经有借阅列表
		userId := session.UserId
		borrow, err := service.GetBorrowByUserId(userId)
		if err != nil {
			borrow = &model.Borrow{}
		}
		if borrow.BorrowId != "" {
			//当前用户已经有借阅记录,判断借阅记录中是否已经借过这本书
			borrowItem, _ := service.GetBorrowItem(int64(bookId), borrow.BorrowId)
			if borrowItem != nil {
				//借阅记录里已经有这本书了,再借的话直接进行数量加一
				log.Println("借阅记录里已经有这本书了")
				borrowItems := borrow.BorrowItem
				for _, v := range borrowItems {
					//找到当前的购物项
					if v.Book.Id == borrowItem.Book.Id {
						if v.Book.Remain > 0 {
							v.BorrowNums++
							//更新该购物项数据库中的count
							service.UpdateBorrowItemNums(v)
							//书里面的借阅量加一，剩余量减一
							v.Book.Borrow++
							v.Book.Remain--
						} else {
							w.Write([]byte("这本书已经被借完"))
						}
						service.UpdateBookNums(v.Book)
						v.Book.IsBorrow = 2
						//更新数据库里的书状态
						err := service.UpdateBookStatus(v.Book)
						if err != nil {
							return
						}
					}
				}
			} else {
				//还没借过这本书,加入这本书
				log.Println("借阅记录里还没借过这本书")
				borrowTime := time.Now().Format("2006-01-02 15:04:05")
				borrowItem := &model.BorrowItem{
					Book:       book,
					BorrowNums: 1,
					BookId:     int64(bookId),
					BorrowId:   borrow.BorrowId,
					BorrowTime: borrowTime,
				}
				borrow.BorrowItem = append(borrow.BorrowItem, borrowItem)
				//保存到数据库
				service.SaveBorrowItem(borrowItem)
				//书里面的借阅量加一，剩余量减一
				if borrowItem.Book.Remain > 0 && borrowItem.Book.Borrow >= 0 {
					borrowItem.Book.Borrow++
					borrowItem.Book.Remain--
				} else {
					w.Write([]byte("这本书已经被借完"))
				}
				service.UpdateBookNums(borrowItem.Book)
				//更新数据库里的书状态
				borrowItem.Book.IsBorrow = 2
				err := service.UpdateBookStatus(borrowItem.Book)
				if err != nil {
					return
				}
			}
			//更新借阅记录里的总数量
			service.UpdateBorrowNums(borrow)
		} else {
			log.Println("该用户还没有借阅记录")
			//该用户还没有借阅记录
			uuid := model.CreateUUID()
			borrow = &model.Borrow{
				BorrowId: uuid,
				UserId:   userId,
			}
			log.Println("创建借阅记录borrow", borrow)
			borrowTime := time.Now().Format("2006-01-02 15:04:05")
			borrowItem := &model.BorrowItem{
				Book:       book,
				BorrowNums: 1,
				BookId:     int64(bookId),
				BorrowId:   uuid,
				BorrowTime: borrowTime,
			}
			//书里面的借阅量加一，剩余量减一
			if borrowItem.Book.Remain > 0 && borrowItem.Book.Borrow >= 0 {
				borrowItem.Book.Borrow++
				borrowItem.Book.Remain--
			} else {
				w.Write([]byte("这本书已经被借完"))
			}
			service.UpdateBookNums(borrowItem.Book)
			//更新数据库里的书状态
			borrowItem.Book.IsBorrow = 2
			err := service.UpdateBookStatus(borrowItem.Book)
			if err != nil {
				return
			}
			var borrowItems []*model.BorrowItem
			borrowItems = append(borrowItems, borrowItem)
			borrow.BorrowItem = borrowItems
			//将borrow添加到数据库里
			service.SaveBorrow(borrow)
			log.Println("success")
		}
		w.Write([]byte("你成功借了" + book.Title + "这本书"))
	} else {
		w.Write([]byte("你还没有登录"))
	}
}

func GetBorrowRecord(w http.ResponseWriter, r *http.Request) {
	_, session := IsLogin(r)
	userId := session.UserId
	borrow, _ := service.GetBorrowByUserId(userId)
	if borrow != nil {
		borrow.Username = session.Username
		borrow.IsLogin = true
		session.Borrow = borrow
		for _, borrowItem := range borrow.BorrowItem {
			bookId := borrowItem.BookId
			//查询book
			book, err := service.BorrowBook(bookId)
			if err != nil {
				return
			}
			borrowItem.Book = book
		}
		t := template.Must(template.ParseFiles("view/pages/book/borrow_list.html"))
		t.Execute(w, borrow)
	} else {
		t := template.Must(template.ParseFiles("view/pages/book/borrow_list.html"))
		t.Execute(w, borrow)
	}
}

func ReturnBook(w http.ResponseWriter, r *http.Request) {
	borrowItemId, _ := strconv.Atoi(r.FormValue("borrowItemId"))
	b := service.QueryBorrowItem(int64(borrowItemId))
	if b {
		_, session := IsLogin(r)
		userId := session.UserId
		//根据userId获取该用户的借阅记录
		borrow, _ := service.GetBorrowByUserId(userId)
		borrowItems := borrow.BorrowItem
		//匹配所有
		for k, v := range borrowItems {
			if v.BorrowItemId == int64(borrowItemId) {
				v.Book.Borrow -= v.BorrowNums
				v.Book.Remain += v.BorrowNums
				service.UpdateBookNums(v.Book)
				//更新数据库里的书状态
				v.Book.IsBorrow = 1
				err := service.UpdateBookStatus(v.Book)
				if err != nil {
					return
				}
				//移除
				borrowItems = append(borrowItems[:k], borrowItems[k+1:]...)
				//更新归还之后
				borrow.BorrowItem = borrowItems
				//将该书数据库中移除
				service.ReturnBookByBorrowItemId(int64(borrowItemId))
			}
		}
		//更新借阅记录的总数量
		service.UpdateBorrowNums(borrow)
		//归还之后再次查询借阅记录
		GetBorrowRecord(w, r)
	} else {
		w.Write([]byte("没有这一项"))
	}

}
